package com.sky.task;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMannerMapper;
import com.sky.mapper.orderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Timer;

/**
 * 定时处理未支付的订单和派送中的订单
 */
@Component
@Slf4j
public class OrderSchedul {
    @Autowired
    private orderMapper orderMapper;
    /**
     * 超时未支付的订单
     */
    //@Scheduled(cron = "0 * * * * ? ")
    private void DeathOrder(){
        //每隔一分钟检查是否有超时订单
        log.info("进来");
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        //ordersPageQueryDTO.setBeginTime(LocalDateTime.now());
        PageHelper.startPage(1,10);
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> result = orders.getResult();
        log.info("订单详情：{}", result.toString());
        if(result.isEmpty()){
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        result.forEach(order -> {
            LocalDateTime orderTime = order.getOrderTime();
            log.info("下单时间：{}",orderTime.toString());
            // 计算时间差
            Duration duration = Duration.between( orderTime,now);
            int i = (int) duration.toMinutes();
            log.info("时间差：{}",i);
            if(i>=15&&(order.getStatus().equals(Orders.PENDING_PAYMENT))){
                order.setCancelTime(now);
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单支付超时");
                log.info("order:{}",order);
                orderMapper.update(order);
            }
        });
        log.info("订单修改成功");
    }
    /**
     * 每天凌晨1点检查是否还有派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    //@Scheduled(cron = "* 57 14 * * ? ")
    private void MannerOrder(){
        //查看所有订单
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        PageHelper.startPage(1,10);
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        orders.forEach(order -> {
            if(order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        });
        log.info("订单完成");
    }
}
